# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

from optparse import OptionParser
from cve_ease import activate_session
import logging

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def check_enabled(gconfig):
    if 'baseline' in gconfig.config and \
            'enabled' in gconfig.config['baseline'] and \
            '1' == gconfig.config['baseline']['enabled']:
        return True
    return False


def handle_baseline(gconfig, db_session, args):
    """[basic] Security stable baseline"""

    usage = "usage: %prog baseline <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    if gconfig.debug:
        print(" * active sql session")

    if not check_enabled(gconfig):
        print("baseline is not enabled! you can modify %s to enable it." % gconfig.configFile)
        exit(0)

    pkgs = None
    if 'pkgs' in gconfig.config['baseline']:
        pkgs = gconfig.config['baseline']['pkgs'].split(',')
        print('baseline pkgs is %s' % pkgs)
    else:
        print('no pkgs found on baseline config')
        exit(1)
    import dnf
    with dnf.Base() as base:
        # Repositories serve as sources of information about packages.
        print("try read_all_repos")
        base.read_all_repos()
        # A sack is needed for querying.
        print("try fill_sack")
        base.fill_sack()

        # https://dnf.readthedocs.io/en/latest/api_queries.html

        print("try query")
        q = base.sack.query()

        print("try available")
        a = q.available()

        print("try filter")
        a = a.filter(name='systemd')

        print("Available dnf packages:")
        for pkg in a:  # a only gets evaluated here
            print('{} in repo {}'.format(pkg, pkg.reponame))
